package edu.uit.se.slgroup.construct.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.uit.se.slgroup.construct.domain.Article;
import edu.uit.se.slgroup.construct.domain.ArticleTemp;
import edu.uit.se.slgroup.construct.domain.SubCategory;
import edu.uit.se.slgroup.construct.services.ArticleService;
import edu.uit.se.slgroup.construct.services.SubCategoryService;

@Controller
public class ArticleController {
	
	@Autowired
	ArticleService articleService;
	
	@Autowired
	SubCategoryService subCategoryService;
	
	@RequestMapping("insert-article-form")
	public ModelAndView getForm(@ModelAttribute Article article) {
		List<SubCategory> subCategoryList = subCategoryService.getSubCategoryList();
		for (SubCategory subCategory : subCategoryList) {
			subCategory.getName();
		}
		System.out.println("in form insert article");
		return new ModelAndView("insert-article", "subCategoryList", subCategoryList);	//insert-article.jsp
	}
	
	@RequestMapping("insertArticle")
	public ModelAndView insertArticle(@ModelAttribute Article article) {
		articleService.insertArticle(article);
		return new ModelAndView("redirect:article-list-form");
	}
	
	@RequestMapping("article-list-form")
	public ModelAndView getArticleList() {
		List<ArticleTemp> articleList = articleService.getArticleTempList();
		System.out.println(" in article list form");
		return new ModelAndView("article-list", "articleList", articleList);	//article-list.jsp
	}
	
	@RequestMapping("deleteArticle")
	public ModelAndView deleteArticle(@RequestParam int id) {
		articleService.deleteArticle(id);
		return new ModelAndView("redirect:article-list-form");
	}
	
	@RequestMapping("edit-article-form")
	public ModelAndView editArticle(@RequestParam int id, @ModelAttribute Article article) {
		Article articleObject = articleService.getArticleById(id);
		
		List<SubCategory> subCategoryList = subCategoryService.getSubCategoryList();
		for (SubCategory subCategory : subCategoryList) {
			subCategory.getName();
		}
		
		ModelAndView mv = new ModelAndView("edit-article");
		mv.addObject("articleObject", articleObject);
		mv.addObject("subCategoryList", subCategoryList);
		return mv;
	}
	
	@RequestMapping("updateArticle")
	public ModelAndView updateArticle(@ModelAttribute Article article) {
		articleService.updateArticle(article);
		return new ModelAndView("redirect:article-list-form");
	}
	
	
}
